package love.contact.engine;

import wwk.common.phone.PhoneCallStateService;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;

public class PhoneService extends PhoneCallStateService{
	
	public static boolean stopCalled=false;

	public void onStart(Intent intent,int startId)
    {
         super.onStart(intent, startId);
         
         TheApplication theApp=(TheApplication)getApplication();
         theApp.engine.getPhoneBook().openOrCreateDatabase(this);
         theApp.engine.setContext(this);
    }
	
	static private void startRepeatAlarm(Context context)
	{
		//send broadcast in periods
		Intent alarmIntent = new Intent(context, PhoneBroadcastReceiver.class);  
		alarmIntent.setAction("love.contact.action.ALARM");  
		PendingIntent sender = PendingIntent.getBroadcast(context, 0,  alarmIntent, 0);  
		
		long firstime = SystemClock.elapsedRealtime();  
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);  
		//10 minites a period
		am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 10*60 * 1000, sender);
	}
	
	static private void cancelAlarm(Context context)
	{
		Intent alarmIntent = new Intent(context, PhoneBroadcastReceiver.class);  
		alarmIntent.setAction("love.contact.action.ALARM"); 
		PendingIntent sender = PendingIntent.getBroadcast(context, 0,  alarmIntent, 0);  
		
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);  
		am.cancel(sender);
	}
	
	static public boolean startService(Context context)
	{
		PhoneService.stopCalled=false;
		ComponentName componentName=context.startService(new Intent(context,PhoneService.class));
		startRepeatAlarm(context);
		
		return componentName!=null;
	}
	
	static public boolean stopService(Context context)
	{
		PhoneService.stopCalled=true;
		cancelAlarm(context);
		return context.stopService(new Intent(context,PhoneService.class));
	}
	
	@Override
    public void onDestroy() 
    { 
   	 	super.onDestroy();
   	 	
   	 	if(!PhoneService.stopCalled)
   	 	{
   	 		PhoneService.startService(this);
   	 	}
    }
}
